package top.lyc829.zzl_android.ui.profile;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Response;
import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.UserInfoBean;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;

public class ProfileViewModel extends ViewModel {

    private MutableLiveData<UserInfoBean> userInfoBeanMutableLiveData;

    public ProfileViewModel() {
        this.userInfoBeanMutableLiveData = new MutableLiveData<>();
    }

    public MutableLiveData<UserInfoBean> getUserInfoBeanMutableLiveData() {
        if(userInfoBeanMutableLiveData == null) {
            userInfoBeanMutableLiveData = new MutableLiveData<>();
        }
        return userInfoBeanMutableLiveData;
    }

    public void getUserInfo() {

        HashMap<String, String> body = new HashMap<>();
        body.put("user_id", Utils.getValueFromSp("user_id"));

        HttpUtil httpUtil = HttpUtil.getInstance(MyApp.getContext());
        httpUtil.get(Url.GET_USER_ALL_INFO, body, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resultStr = res.body().string();

                Utils.Sout(resultStr);
                ResultBean<UserInfoBean> resultBean = JsonUtilNew.fromJsonObject(resultStr, UserInfoBean.class);

                if (resultBean.getCode().equals(200)) {
                    getUserInfoBeanMutableLiveData().postValue(resultBean.getData());
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }

            }

            @Override
            public void failed(IOException e) {
                Utils.SoutErr(e.getMessage());
            }
        });

    }

}